package com.uduew.sjd.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;

import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.uduew.sjd.R;

import java.util.ArrayList;
import java.util.List;

public class CodeInputView extends LinearLayout {
    private int boxCount = 6;
    private int boxSize = dpToPx(41);
    private int boxSpacing = dpToPx(8);
    private Drawable boxBackground;
    private List<AppCompatEditText> codeBoxes = new ArrayList<>();
    private OnCodeCompleteListener listener;

    public CodeInputView(Context context) {
        super(context);
        init(null);
    }

    public CodeInputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CodeInputView);
            boxCount = a.getInt(R.styleable.CodeInputView_boxCount, 6);
            boxSize = a.getDimensionPixelSize(R.styleable.CodeInputView_boxSize, dpToPx(41));
            boxSpacing = a.getDimensionPixelSize(R.styleable.CodeInputView_boxSpacing, dpToPx(8));
            boxBackground = a.getDrawable(R.styleable.CodeInputView_boxBackground);
            a.recycle();
        }

        if (boxBackground == null) {
            boxBackground = ContextCompat.getDrawable(getContext(), R.drawable.bg_code_box);
        }

        setOrientation(HORIZONTAL);
        setGravity(Gravity.CENTER);

        // 关键修改：使用边距替代权重实现精确间距控制
        for (int i = 0; i < boxCount; i++) {
            addCodeBox(i);
        }
    }

    // 在CodeInputView类中添加方法
    public void clearAll() {
        for (AppCompatEditText box : codeBoxes) {
            box.setText("");
        }
        // 将焦点重置到第一个输入框
        if (!codeBoxes.isEmpty()) {
            codeBoxes.get(0).requestFocus();
        }
    }


    private void addCodeBox(int position) {
        AppCompatEditText editText = new AppCompatEditText(getContext());
        LayoutParams params = new LayoutParams(boxSize, boxSize);
        // 设置边距实现间距
        if (position == 0) {
            // 第一个框只有右边距
            params.setMargins(0, 0, boxSpacing, 0);
        } else if (position == boxCount - 1) {
            // 最后一个框只有左边距
            params.setMargins(boxSpacing, 0, 0, 0);
        } else {
            // 中间框两边都有边距
            params.setMargins(boxSpacing, 0, boxSpacing, 0);
        }

        editText.setLayoutParams(params);
        editText.setFilters(new InputFilter[]{
                new InputFilter.LengthFilter(1)
        });
        editText.setBackground(boxBackground);
        editText.setGravity(Gravity.CENTER);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        editText.setMaxLines(1);
        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
        // 光标可见性控制
//        editText.setCursorVisible(editText.hasFocus());
//        editText.setOnFocusChangeListener((v, hasFocus) -> {
//            editText.setCursorVisible(hasFocus);
//            if (hasFocus && isAllEmpty()) {
//                codeBoxes.get(0).requestFocus();
//            }
//        });

        final int pos = position;
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 1 && pos < boxCount - 1) {
                    codeBoxes.get(pos + 1).requestFocus(); // 正向输入跳转
                }
                // 完全移除删除时的自动跳转逻辑
                checkCompletion();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        editText.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (editText.getText().length() > 0) {
                    editText.setText(""); // 直接清空当前有内容的框
                    return true;
                } else if (pos > 0) {
                    AppCompatEditText prevBox = codeBoxes.get(pos - 1);
                    prevBox.setText(""); // 仅清空前一个框内容
                    prevBox.requestFocus(); // 焦点移到前一个框
                    return true;
                }
            }
            return false;
        });

        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus && isAllEmpty()) {
                codeBoxes.get(0).requestFocus();
            }
        });

        codeBoxes.add(editText);
        addView(editText);
    }
    // 新增辅助方法：判断所有输入框是否为空
    private boolean isAllEmpty() {
        for (AppCompatEditText box : codeBoxes) {
            if (!box.getText().toString().isEmpty()) {
                return false;
            }
        }
        return true;
    }
    private void addSpaceBetweenBoxes() {
        View space = new View(getContext());
        LayoutParams params = new LayoutParams(0, 0);
        params.weight = 0.5f; // 间隔权重为0.5
        space.setLayoutParams(params);
        addView(space);
    }

    private void checkCompletion() {
        if (listener != null) {
            StringBuilder code = new StringBuilder();
            for (AppCompatEditText box : codeBoxes) {
                code.append(box.getText().toString());
            }
//            if (code.length() == boxCount) {
                listener.onCodeComplete(code.toString());
//            }
        }
    }

    public void setOnCodeCompleteListener(OnCodeCompleteListener listener) {
        this.listener = listener;
    }

    public interface OnCodeCompleteListener {
        void onCodeComplete(String code);
    }

    private int dpToPx(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }
}